var _that
var app = getApp()
var allCarGoods = {}
var timeId
var {getNodeRef, keepTwoDecimalFull, formatDate, dayAfter} = require('../../utils/util')

function carInit(target) {
  _that = target
  _that.setData({
    cartype: 'bread',
    showCartCnt: false,
    showCart: false,
    cartAdded: false,
    cartFly: false,
    curCartImg: '',
    goodslist: [],
    goodsidlist: [],
    flyStyle: {},
    flyInStyle: {}
  })
  allCarGoods = {}
  loadCarData()
}

function showDetail() {
  if (_that.data.totalcount <= 0) {
    return
  }
  _that.setData({
    showCart: true
  })
  _that.setData({
    showCartCnt: true
  })
}

function closeDetail() {
  _that.setData({
    showCartCnt: false
  })
  setTimeout(() => {
    _that.setData({
      showCart: false
    })
  }, 300)
}

function toggleDetail() {
  if (_that.data.showCart) {
    closeDetail()
  } else {
    showDetail()
  }
}

function update() {

}

function submitOrder(orderinfo) {
  if (_that.data.address == null || _that.data.address === undefined) {
    app.toast.error('请先添加收货地址！')
    return
  }

  if (_that.data.totalcount <= 0) {
    return
  }

  var curdate = _that.data.breadType === '3'
    ? formatDate(dayAfter(new Date, 1), 'yyyyMMdd')
    : formatDate(new Date, 'yyyyMMdd')
  var url = `/yuanmai_we/activity/checkShoppingCart/${curdate}`
  var params = {
    __zaofans: true
  }

  var property = {
    meals: _that.data.goodslist,
    cityId: app.globalData.address.CITYID
  }

  if (_that.data.breadType === '2') {
    property.storeId = _that.data.storeId
  }

  params.datas = JSON.stringify(property)
  app.request(url, params).then(checkCartCallBack)
}

function checkCartCallBack(res) {
  var isEnough = true
  var goodsindex
  var stockinfo = res.stockArray
  var goodslist = _that.data.goodslist
  var goodsidlist = _that.data.goodsidlist
  for (var i = 0; i < stockinfo.length; i++) {
    if (stockinfo[i].STOCK.stationStockStatus === false) {
      isEnough = false
      goodsindex = goodsidlist.indexOf(stockinfo[i].ID)
      goodslist[goodsindex].noStock = '1'
    }
    else {
      goodsindex = goodsidlist.indexOf(stockinfo[i].ID)
      goodslist[goodsindex].noStock = '0'
      stockinfo[i].STOCK.synthesisNotExistStatus = false
      stockinfo[i].STOCK.synthesisNotStatus = false
      stockinfo[i].STOCK.synthesisAndStatus = true
      stockinfo[i].STOCK.synthesisOrStatus = true
      stockinfo[i].STOCK.synthesisXOrStatus = false
    }
  }
  if (isEnough === false) {
    _that.setData({
      goodslist: goodslist
    })
    showDetail()
  }
  else {
    wx.navigateTo({
      url: '../neworder/neworder?type=bread&orderinfo=' + encodeURIComponent(JSON.stringify(stockinfo)) + '&address=' + encodeURIComponent(JSON.stringify(_that.data.address)) + '&stationId=' + _that.data.stationId + '&storeId=' + _that.data.storeId + '&breadType=' + _that.data.breadType
    })
  }
}

function startBounce() {
  _that.setData({
    cartAdded: true
  })

  if (timeId) {
    clearTimeout(timeId)
  }
  timeId = setTimeout(() => {
    _that.setData({
      cartAdded: false
    })
  }, 1000)
}

function startFly(id, imgUrl) {
  if (_that.data.cartFly) return

  Promise.all([getNodeRef(id), getNodeRef("#cart_icon")]).then(res => {
    var addNodeRef = res[0]
    var cartNodeRef = res[1]

    _that.setData({
      cartFly: true,
      curCartImg: imgUrl,
      flyStyle: {
        left: addNodeRef.left,
        top: addNodeRef.top
      }
    })

    _that.setData({
      flyStyle: {
        left: addNodeRef.left,
        top: addNodeRef.top,
        transform: 'translate3d(0,' + (cartNodeRef.top - addNodeRef.top) + 'px,0)'
      },
      flyInStyle: {
        transform: 'translate3d(' + (cartNodeRef.left - addNodeRef.left + 8) + 'px,0,0)',
        width: 10,
        height: 10
      }
    })

    setTimeout(() => {
      startBounce()
      _that.setData({
        cartFly: false,
        curCartImg: '',
        flyStyle: {},
        flyInStyle: {}
      })
    }, 800)

  })
}

function handleCount(e) {
  var options, goodsid
  if (e.currentTarget) {
    options = parseInt(e.currentTarget.dataset.options)
    goodsid = e.currentTarget.dataset.goodsid
  } else {
    options = e.options
    goodsid = e.goodsid
  }
  var anchor = e.currentTarget.dataset.anchor
  var curIndex = 0
  var keyid = 0
  var goodslist = _that.data.goodslist
  var goodsidlist = _that.data.goodsidlist
  var breadlist = _that.data.breadlist
  var totalcount = parseInt(_that.data.totalcount)
  var totalprice = parseFloat(_that.data.totalprice)

  for (var i = 0; i < breadlist.length; i++) {
    keyid = breadlist[i].goodsid
    curIndex = goodsidlist.indexOf(keyid)
    if (keyid === goodsid) {
      if (Number(options) === 1) {
        totalcount += 1
        totalprice += parseFloat(breadlist[i].price)
        if (curIndex >= 0) {
          goodslist[curIndex].COUNT = parseInt(goodslist[curIndex].COUNT) + 1
          startFly('#addcart_' + anchor + '_' + goodsid, goodslist[curIndex].img)
        } else {
          goodsidlist.push(keyid)
          goodslist.push({
            goodsid: keyid,
            ID: keyid,
            MEALID: breadlist[i].mealid,
            COUNT: '1',
            name: breadlist[i].name,
            price: breadlist[i].price,
            img: breadlist[i].img
          })
          startFly('#addcart_' + anchor + '_' + goodsid, breadlist[i].img)
        }
      } else {
        if (totalcount > 0 && curIndex >= 0) {
          totalcount -= 1
          totalprice -= parseFloat(breadlist[i].price)
          goodslist[curIndex].COUNT = parseInt(goodslist[curIndex].COUNT) - 1
          if (parseInt(goodslist[curIndex].COUNT) <= 0) {
            goodslist.splice(curIndex, 1)
            goodsidlist.splice(curIndex, 1)
          }
        }
      }
      break
    }
  }

  totalprice = keepTwoDecimalFull(totalprice)
  _that.setData({
    totalcount: totalcount,
    totalprice: totalprice,
    goodslist: goodslist,
    goodsidlist: goodsidlist
  })

  var oldgoods
  if (allCarGoods[_that.data.breadtype] != null && allCarGoods[_that.data.breadtype] !== undefined) {
    oldgoods = allCarGoods[_that.data.breadtype]
  } else {
    oldgoods = {}
  }
  oldgoods.totalcount = totalcount
  oldgoods.totalprice = totalprice
  oldgoods.goodslist = goodslist
  oldgoods.goodsidlist = goodsidlist
  allCarGoods[_that.data.breadtype] = oldgoods

  if (totalcount === 0) {
    _that.setData({
      showCart: false
    })
  }
}

function resetCar() {
  if (allCarGoods[_that.data.breadtype] != null && allCarGoods[_that.data.breadtype] !== undefined) {
    var oldGoods = allCarGoods[_that.data.breadtype]
    _that.setData({
      totalcount: oldGoods.totalcount,
      totalprice: oldGoods.totalprice,
      goodslist: oldGoods.goodslist,
      goodsidlist: oldGoods.goodsidlist
    })
  }
  else {
    _that.setData({
      totalcount: 0,
      totalprice: 0.00,
      goodslist: [],
      goodsidlist: []
    })
  }
}

function checkGoodsCount(goodsid) {
  if (allCarGoods[_that.data.breadtype] == null || allCarGoods[_that.data.breadtype] === undefined) {
    return 0
  }
  else {
    var oldgoods = allCarGoods[_that.data.breadtype].goodslist
    var goodsnum = 0
    for (var i = 0; i < oldgoods.length; i++) {
      if (oldgoods[i].MEALID === goodsid) {
        goodsnum = oldgoods[i].COUNT
        break
      }
    }
    return goodsnum
  }
}

module.exports = {
  init: carInit,
  showCar: showDetail,
  closeCar: closeDetail,
  toggleCar: toggleDetail,
  update: update,
  submitOrder: submitOrder,
  handleCount: handleCount,
  reset: resetCar,
  checkGoodsCount: checkGoodsCount
}

//------以下方法不外调
function loadCarData() {
  var totalcount = 0
  var totalprice = 0.00
  _that.setData({
    totalcount: totalcount,
    totalprice: totalprice,
    goodslist: [],
    goodsidlist: []
  })
}
